<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="160px">
      <el-form-item label="标题："  prop="title">
        <el-input type="text" v-model="form.title"/>
      </el-form-item>
      <el-form-item label="内容：" prop="content">
        <Tinymce v-model="form.content" :height="300" id="Tinymce"></Tinymce>
      </el-form-item>
      <el-form-item label="附件列表：">
        <div v-if="form.attachments.length">
          <el-card class="box-card" v-for="(item,index) in form.attachments" :key="index">
            <span class="removed" @click="removeName(index)">X</span>
            <el-form label-width="90px">
              <el-form-item label="附件名称：">
                <el-input type="text" v-model="item.name" aria-placeholder="请输入附件名称"/>
              </el-form-item>
               <el-form-item label="文件类型：" style="margin-top:20px">
                 <el-select v-model="item.type" placeholder="请选择文件类型" style="width:100%">
                    <el-option
                      v-for="item in type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
               </el-form-item>
               <el-form-item label="附件描述：" style="margin-top:20px">
                <el-input type="text" v-model="item.desc" aria-placeholder="请输入附件描述"/>
              </el-form-item>
               <el-form-item label="上传文件：" style="margin-top:20px">
                <el-upload
                  action="https://knowledge.nervenets.com/api/v1/file/upload"
                  list-type="text"
                  :on-remove="handleRemove"
                  :on-success="(res)=>{handleAvatarSuccess(res,index)}"
                  :before-upload="(file)=>{return beforeAvatarUpload(file,item,index)}"
                  :show-file-list="false"
                  name="userfile"
                >
                    <img style="margin-top: -1px;margin-left:-1px;width: 150px;height: 150px;border-radius: 6px" v-if="item.url&&item.type=='image'"  :src="item.url" class="avatar">
                    <audio :src="item.url" ref="audio" v-if="item.url&&item.type=='audio'" :controls="item.url"></audio>
                    <!-- <embed :src="item.url" v-if="item.url"> -->
                    <i v-if="!item.url" class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
        <el-button @click="addAth">添加附件</el-button>
      </el-form-item>
        <el-form-item  label="标签选择：" prop="eleList" v-if="eleList.length">
                <el-checkbox-group v-model="form.tagsIds" size="medium">
                    <el-checkbox-button v-for="(item,index) in eleList" :label="item.id" :key="index">{{item.name}}</el-checkbox-button>
                </el-checkbox-group>
        </el-form-item>
      <el-form-item>
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" :loading="loading"  @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { edit,detail } from '@/api/culture'
  import {list} from '@/api/tag'
  import { getToken } from '@/utils/auth'
  import {showDecimal} from '@/utils'
  import Tinymce from '@/components/Tinymce'
  export default {
    data() {
      return {
        type:[
          {
          value: 'text',
          label: '文本'
        },{
          value: 'image',
          label: '图片'
        },{
          value: 'audio',
          label: '音频'
        },{
          value: 'video',
          label: '视频'
        },{
          value: 'pdf',
          label: 'pdf'
        },{
          value: 'word',
          label: 'word'
        },{
          value: 'excel',
          label: 'excel'
        },
        ],
        loading:false,
        id:0,
        form: {
          attachments:[],
          managerId:0,
          token:getToken(),
          content:'',
          tagsIds:[],
          title:''
        },
        rules:{
          title: [
            { required: true, message: '请输入名称', trigger: 'blur' },
          ]
        },
        eleList:[]
      }
    },
    methods: {
      removeName(index) {
        this.form.attachments.splice(index, 1)
      },
    handleRemove(file) {
      console.log(file);
    },
    handleAvatarSuccess(res,index){
       if(this.form.attachments[index].type=='audio'){
         this.getTime(index)
        }
      this.form.attachments[index].url=res.data
    },
    beforeAvatarUpload(file,item,index) {
        if(!item.type){
           this.$message({
            showClose: true,
            message: '请先选择文件类型',
            type: 'error'
          });
          return false
        }
        if(item.type=='image'){
          this.form.attachments[index].length=file.size
        }
    },
    getTime(index){
       setTimeout(()=>{
        let test = this.$refs.audio;
        let j=-1;
        for(let i=0;i<=index;i++){
          if(this.form.attachments[i].type=="audio"){
            j++;
          }
        }
        setTimeout(()=>{
          this.form.attachments[index].length=parseInt(test[j].duration)
        },1000)
      },1000)
    },
      addAth(){
        this.form.attachments.push({
          desc:'',
          length:0,
          name:'',
          type:'',
          url:''
        })
      },
      getDetails(){
          detail({targetId:this.$route.query.id}).then((json) => {
            if(json.status === 200){
               this.form.title=json.data.title;
               this.form.content=json.data.content;
               this.form.knowledgeId=json.data.id;
               json.data.attachments.map((r)=>{
                 r.type=r.type.value
               })
               this.form.attachments=json.data.attachments;
               for(let item of json.data.tags){
                   this.form.tagsIds.push(item.id)
               }
              }else{
                this.$message.error(json.data.message);
              }
          });
        },
        getEle(){
            list({managerId:this.$route.query.managerId}).then((json) => {
            if(json.status === 200){
               let test =[];
               for(let i=0;i<json.data.length;i++){
                 if(!json.data[i].enable){
                   test.push(json.data[i])
                 }
               }
              this.eleList=test;
              }else{
                this.$message.error(json.data.message);
              }
          });
        },
      onSubmit() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.loading=true
            let data=JSON.parse(JSON.stringify(this.form))
            edit(data).then(res=>{
              this.$message.success('添加(编辑)成功')
              this.onCancel()
            }).finally(()=>{
              this.loading=false
            })
          }
        });
      },
      onCancel() {
        this.$router.go(-1)
      }
    },
    created() {
      this.form.managerId=this.$route.query.managerId;
      this.getEle();
      if(this.$route.query.id){
        this.getDetails();
      } 
    },
    components:{
        Tinymce
    }
  }
</script>

<style lang="scss" scoped>
  .app-container{
    width: 780px;
  }
  .line{
    text-align: center;
  }
  .box-card{
    margin-bottom: 30px;
    position: relative;
  }
  .removed{
    position: absolute;
    right: 1%;
    top: -3%;
    cursor: pointer;
  }
</style>
